export function formatWeek(week) {
  switch (week) {
    case 1:
      return '星期一';
    case 2:
      return '星期二';
    case 3:
      return '星期三';
    case 4:
      return '星期四';
    case 5:
      return '星期五';
    case 6:
      return '星期六';
    case 0:
      return '星期日';
  }
}

export function weekFormat(week) {
  switch (week) {
    case 1:
      return '周一';
    case 2:
      return '周二';
    case 3:
      return '周三';
    case 4:
      return '周四';
    case 5:
      return '周五';
    case 6:
      return '周六';
    case 0:
      return '周日';
  }
}

export function getBetweenDate(startTime, endTime) {
  // 校验时间格式
  if (typeof startTime === 'string') {
    const reg = /^\d{4}-(0?[1-9]|1[0-2])-((0?[1-9])|((1|2)[0-9])|30|31)$/g
    if (!reg.test(startTime)) throw `开始时间：${startTime}时间格式错误`
  }
  if (typeof endTime === 'string') {
    const reg = /^\d{4}-(0?[1-9]|1[0-2])-((0?[1-9])|((1|2)[0-9])|30|31)$/g
    if (!reg.test(endTime)) throw `结束时间：${endTime}时间格式错误`
  }
  let start = new Date(startTime)
  let end = new Date(endTime)
  const resultTime = []
  // 当 开始时间小于结束时间的时候进入循环
  while (start <= end) {
    let getDay = start.getDate()
    // 月份需要加 1
    let getMonth = start.getMonth() + 1
    let getYear = start.getFullYear()
    /**
     * 拼接时间格式
     * (getMonth >= 10 ? `${getMonth}` : `0${getMonth}`) 自动给 小于10的时间前面补0
     */
    let setTime =
      `${getYear}-` +
      (getMonth >= 10 ? `${getMonth}` : `0${getMonth}`) +
      '-' +
      (getDay >= 10 ? `${getDay}` : `0${getDay}`)

    resultTime.push(setTime)
    /**
     * 重新设置开始时间
     * 使用 setFullYear() 方法会自动将时间累加，返回的是时间戳格式
     * 使用 new Date() 将时间重新设置为标准时间
     * getMonth - 1 将月份时间重新还原
     */
    start = new Date(start.setFullYear(getYear, getMonth - 1, getDay + 1))
  }
  return resultTime
}


let DATE_FORMAT = /^(\d{4})(-)(\d{2})(-)(\d{2})$/;

export function formatTimeAddWeek(begin, end, day) {
  let weekArr = [];
  let arr = formatBeginAndEndTimeList(begin, end);
  if (arr.length > 0) {
    arr.forEach(item => weekArr.push(item + ' ' + formatWeek(day(item).day())));
  }
  return weekArr;
}

/**
 *  根据传入的多选日期计算值
 * @param dataArr   ['2023-01-31', '2023-02-01']
 * @returns {[]}
 */
export function formatTimeMultiple(dataArr, day) {
  let weekArr = [];
  if (dataArr.length == 0) {
    return weekArr;
  }
  dataArr.forEach(item => weekArr.push(item + ' ' + formatWeek(day(item).day())));
  return weekArr;
}

/**
 * 计算总日期列表
 * @param begin 2022-10-10
 * @param end   2022-10-20
 * @returns {*[]}
 */
export function formatBeginAndEndTimeList(begin, end) {
  if (begin.match(DATE_FORMAT) == null || end.match(DATE_FORMAT) == null) {
    return null;
  }
  if (Date.parse(begin) > Date.parse(end)) {
    return null;
  }
  let arr1 = begin.split('-');   //这里可以换成/  就2020/01/1 这种
  let arr2 = end.split('-');
  let arr1_ = new Date();
  let arrTime = [];
  arr1_.setUTCFullYear(arr1[0], arr1[1] - 1, arr1[2]);
  let arr2_ = new Date();
  arr2_.setUTCFullYear(arr2[0], arr2[1] - 1, arr2[2]);
  let unixDb = arr1_.getTime();
  let unixDe = arr2_.getTime();
  for (let k = unixDb; k <= unixDe;) {
    arrTime.push(datetimeparse(k, 'YY-MM-DD'));
    k = k + 24 * 60 * 60 * 1000;
  }
  return arrTime;
}

// 时间格式处理
export function datetimeparse(timestamp, format, prefix) {
  if (typeof timestamp == 'string') {
    timestamp = Number(timestamp)
  }
  //转换时区
  let currentZoneTime = new Date(timestamp);
  let currentTimestamp = currentZoneTime.getTime();
  let offsetZone = currentZoneTime.getTimezoneOffset() / 60; //如果offsetZone>0是西区，西区晚
  let offset = null;
  //客户端时间与服务器时间保持一致，固定北京时间东八区。
  offset = offsetZone + 8;
  currentTimestamp = currentTimestamp + offset * 3600 * 1000

  let newtimestamp = null;
  if (currentTimestamp) {
    if (currentTimestamp.toString().length === 13) {
      newtimestamp = currentTimestamp.toString()
    } else if (currentTimestamp.toString().length === 10) {
      newtimestamp = currentTimestamp + '000'
    } else {
      newtimestamp = null
    }
  } else {
    newtimestamp = null
  }
  let dateobj = newtimestamp ? new Date(parseInt(newtimestamp)) : new Date()
  let YYYY = dateobj.getFullYear()
  let MM = dateobj.getMonth() > 8 ? dateobj.getMonth() + 1 : '0' + (dateobj.getMonth() + 1)
  let DD = dateobj.getDate() > 9 ? dateobj.getDate() : '0' + dateobj.getDate()
  let HH = dateobj.getHours() > 9 ? dateobj.getHours() : '0' + dateobj.getHours()
  let mm = dateobj.getMinutes() > 9 ? dateobj.getMinutes() : '0' + dateobj.getMinutes()
  let ss = dateobj.getSeconds() > 9 ? dateobj.getSeconds() : '0' + dateobj.getSeconds()
  let output = '';
  let separator = '/'
  if (format) {
    separator = format.match(/-/) ? '-' : '/'
    output += format.match(/yy/i) ? YYYY : ''
    output += format.match(/MM/) ? (output.length ? separator : '') + MM : ''
    output += format.match(/dd/i) ? (output.length ? separator : '') + DD : ''
    output += format.match(/hh/i) ? (output.length ? ' ' : '') + HH : ''
    output += format.match(/mm/) ? (output.length ? ':' : '') + mm : ''
    output += format.match(/ss/i) ? (output.length ? ':' : '') + ss : ''
  } else {
    output += YYYY + separator + MM + separator + DD
  }
  output = prefix ? (prefix + output) : output
  return newtimestamp ? output : ''
}

/**
 *  根据开始时间和结束时间，以step为切割时间，获取数组
 * @param startTime 03:00
 * @param endTime   06:00
 * @param step 60
 * @returns {*['03:00', '04:00', '05:00']}
 */
export function timeSlot(startTime, endTime, step) {
  let timeArr = [];
  // 校验时间格式
  if (step < 0) {
    throw `${step} 不能小于0`;
  }
  if (startTime.length == 8) {
    startTime = startTime.substring(0, 5);
  }
  if (endTime.length == 8) {
    endTime = endTime.substring(0, 5);
  }
  if (typeof startTime === 'string' && typeof endTime === 'string') {
    // const reg = /^(0?[1-9]|([1-2][0-4])):(([0-5][0-9])(:([0-9][0-9]))?)$/
    const reg = /^(([0-1]\d)|(2[0-4])):[0-5]\d$/
    if (!reg.test(startTime)) throw `开始时间：${startTime} 时间格式错误`
    if (!reg.test(endTime)) throw `结束时间：${endTime} 时间格式错误`
  } else {
    throw `${startTime} 或者 ${endTime} 时间格式错误`
  }
  let dateBegin = new Date('2018/10/11 ' + startTime);
  let dateEnd = new Date('2018/10/11 ' + endTime);
  if (isNaN(dateBegin) || isNaN(dateEnd)) {
    return null;
  }
  let timeBegin = dateBegin.getTime();
  let timeEnd = dateEnd.getTime();
  let differ = timeEnd - timeBegin;
  if (differ < 0) {
    throw `${startTime} 不能小于 ${endTime}`;
  }
  let minDiffer = differ / 60 / 1000;   // 转为分钟
  let slotNum = parseInt(minDiffer / step); // 算出多少个间隔,向上取整，小数丢弃
  for (let f = 0; f < slotNum; f++) {
    let time = new Date(
      Number(dateBegin.getTime()) + Number(step * 60 * 1000 * f)
    ); // 获取：零点的时间 + 每次递增的时间
    let hour = '',
      sec = '';
    time.getHours() < 10
      ? (hour = '0' + time.getHours())
      : (hour = time.getHours()); // 获取小时
    time.getMinutes() < 10
      ? (sec = '0' + time.getMinutes())
      : (sec = time.getMinutes()); // 获取分钟
    timeArr.push(hour + ':' + sec);
  }
  return timeArr;
}

/**
 * 根据开始时间和时间间隔，得到结束时间
 * @param startTime '03:00'
 * @param step 60
 * @returns '04:00'
 */
export function calcEndtimeSlot(startTime, step) {
  let endTime = '';
  if (step < 0) {
    throw `${step} 不能小于0`;
  }
  if (typeof startTime === 'string') {
    const reg = /^(([0-1]\d)|(2[0-4])):[0-5]\d$/
    if (!reg.test(startTime)) throw `开始时间：${startTime} 时间格式错误`
  } else {
    throw `${startTime} 时间格式错误`
  }
  let dateBegin = new Date('2018/10/11 ' + startTime);
  if (isNaN(dateBegin)) {
    return null;
  }
  let time = new Date(Number(dateBegin.getTime()) + Number(step * 60 * 1000));
  let hour = '',
    sec = '';
  time.getHours() < 10
    ? (hour = '0' + time.getHours())
    : (hour = time.getHours()); // 获取小时
  time.getMinutes() < 10
    ? (sec = '0' + time.getMinutes())
    : (sec = time.getMinutes()); // 获取分钟
  endTime = hour + ':' + sec;
  return endTime;
}


export function getNextWeekData(treeType = 8) {
  let myDate = new Date();
  const dateArray = [];
  const dateArrayTemp = [];
  for (let i = 0; i < treeType; i++) {
    let tt = formatDate(myDate);
    let t = tt.replace(/\-/g, ".");
    dateArray.push(t.substring(5, 10));
    dateArrayTemp.push(myDate.toLocaleDateString());
    myDate.setDate(myDate.getDate() + 1);
  }
  let newArr = []
  for (let i = 0; i < dateArray.length; i++) {
    newArr.push({
      date: dateArray[i],
      week: weekFormat(new Date(dateArrayTemp[i]).getDay()),
    })
  }
  return newArr;
}


// export function getTwoWeekData(date, days = 14) {
//   if (typeof date != 'object') {
//     throw `${date} 时间格式错误`
//   }
//   let startWeek = new Date(getStartDayOfWeek(date));
//   const dateArray = [];
//   const dateArrayTemp = [];
//   for (let i = 0; i < days; i++) {
//     // let time = new Date(new Date("2023-02-22").format('yyyy-MM-dd') + " 00:00:00");
//     let time = new Date(new Date().format('yyyy-MM-dd') + " 00:00:00").getTime();
//     let timeStart = startWeek.getTime();
//     if (time <= timeStart) {
//       let tt = formatDate(startWeek);
//       let t = tt.replace(/\-/g, ".");
//       dateArray.push(t.substring(5, 10));
//       dateArrayTemp.push(startWeek.toLocaleDateString());
//     }
//     startWeek.setDate(startWeek.getDate() + 1);
//   }
//   let newArr = []
//   for (let i = 0; i < dateArray.length; i++) {
//     newArr.push({
//       date: dateArray[i],
//       week: weekFormat(new Date(dateArrayTemp[i]).getDay()),
//       fullDate: new Date(dateArrayTemp[i]),
//     })
//   }
//   return newArr;
// }
//
// //获得本周的开始时间：
// function getStartDayOfWeek(now) {
//   // let now = new Date(); // 当前日期
//   let nowDayOfWeek = now.getDay(); // 今天本周的第几天
//   let day = nowDayOfWeek || 7;//0-6，周日是0
//   let nowDay = now.getDate(); // 当前日
//   let nowMonth = now.getMonth(); // 当前月
//   return formatDate(new Date(now.getFullYear(), nowMonth, nowDay + 1 - day));//关键代码
// };

function formatDate(date) {
  let myYear = date.getFullYear();
  let myMonth = date.getMonth() + 1;
  let myWeekday = date.getDate();
  let myHour = date.getHours();
  let myMinute = date.getMinutes();
  let mySecond = date.getSeconds();

  if (myMonth < 10) {
    myMonth = '0' + myMonth;
  }
  if (myWeekday < 10) {
    myWeekday = '0' + myWeekday;
  }
  if (myHour < 10) {
    myHour = '0' + myHour;
  }
  if (myMinute < 10) {
    myMinute = '0' + myMinute;
  }
  if (mySecond < 10) {
    mySecond = '0' + mySecond;
  }
  return (`${myYear}-${myMonth}-${myWeekday} ${myHour}:${myMinute}:${mySecond}`);
}




export function getTwoWeekData(date, days = 14) {
  if (!(date instanceof Date)) {
    throw new Error(`${date} 时间格式错误`);
  }
  const startWeek = getStartDayOfWeek(date);
  const dateArray = [];
  for (let i = 0; i < days; i++) {
    const currentDate = new Date(startWeek.getTime() + i * 86400000);
    const currentDateString = `${currentDate.getFullYear()}.${(currentDate.getMonth() + 1).toString().padStart(2, '0')}.${currentDate.getDate().toString().padStart(2, '0')}`;
    const now = new Date();
    const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    let timeStart = currentDate.getTime();
    if (startOfDay <= timeStart) {
      dateArray.push({
        date: currentDateString.substring(5),
        week: weekFormat(currentDate.getDay()),
        fullDate: currentDate,
      });
    }
  }
  return dateArray;
}

function getStartDayOfWeek(now) {
  const nowDayOfWeek = now.getDay();
  const day = nowDayOfWeek === 0 ? 6 : nowDayOfWeek - 1;
  const nowDay = now.getDate();
  const nowMonth = now.getMonth();
  return new Date(now.getFullYear(), nowMonth, nowDay - day);
}



export function formateBeginAndEndDate(dateRange, type = '1') {
  if (dateRange.length != 2) {
    throw `${dateRange} 格式错误`
  }
  if (typeof dateRange[0] == 'string' && typeof dateRange[1] == 'string') {
    let paramArr = [];
    let begin = datetimeparse(new Date(dateRange[0]).getTime(), 'yyyy-MM-DD');
    let end = datetimeparse(new Date(dateRange[1]).getTime(), 'yyyy-MM-DD');
    if (type == '1') {
      paramArr.push(begin + ' 00:00:00');
      paramArr.push(end + ' 23:59:59');
    } else {
      paramArr.push(begin);
      paramArr.push(end);
    }
    return paramArr;
  } else if (typeof dateRange[0] == 'object' && typeof dateRange[1] == 'object') {
    let paramArr = [];
    let begin = datetimeparse(dateRange[0].getTime(), 'yyyy-MM-DD');
    let end = datetimeparse(dateRange[1].getTime(), 'yyyy-MM-DD');
    if (type == '1') {
      paramArr.push(begin + ' 00:00:00');
      paramArr.push(end + ' 23:59:59');
    } else {
      paramArr.push(begin);
      paramArr.push(end);
    }
    return paramArr;
  }
}

export function calcServiceDate(beginDate, endDate, str = '-') {
  if (typeof beginDate != 'string' && typeof endDate != 'string') {
    throw `${beginDate} 或者 ${endDate} 格式错误`
  }
  let date = beginDate.substring(0, 4) + str + beginDate.substring(5, 7) + str + beginDate.substring(8, 10);
  let beginDateStr = beginDate.substring(11, 16);
  let endDateStr = endDate.substring(11, 16);
  let val = date + '(' + beginDateStr + "~" + endDateStr + ')';
  return val
}


export function calcHHmm(hhmm, arr, str = '+') {
  if (typeof hhmm != 'string') {
    throw `${hhmm} 格式错误`
  }
  if (arr < 0) {
    throw `${arr} 不能小于0`;
  }
  let dat = new Date().format('yyyy-MM-dd').substring(0, 4) + "-" + hhmm.substring(0, 2) + "-" + hhmm.substring(3, 5) + " 00:00:00";
  let date = getDate(dat);
  if (str === '+') {
    date.setDate(date.getDate() + 1);
  } else {
    date.setDate(date.getDate() - 1);
  }
  let val = date.format('yyyy-MM-dd').replace(/\-/g, ".").substring(5, 10);
  let ff = arr.filter(a => a.date == val);
  if (ff.length > 0) {
    return ff[0];
  } else {
    return '';
  }
}

//兼容 IOS new date
export function getDate(strdate) {
  var arr = strdate.split(/[- : \/]/);
  var date = new Date(arr[0], arr[1] - 1, arr[2], arr[3], arr[4], arr[5]);
  return date;
}

